<?php

class Tinyask_Date
{
	/**
	 * 期望时区
	 *
	 * @var integer
	 */
	public static $timezone = 0;

	/**
	 * 服务器所在时区
	 *
	 * @var integer
	 */
	public static $serverTimezone = 0;

	/**
	 * 当前GMT时间戳
	 *
	 * @var integer
	 */
	public static $gmtTimestamp;

	/**
	 * 可以被直接转换的时间戳
	 *
	 * @var integer
	 */
	public $timestamp = 0;

	/**
	 * 初始化, 转化为期望时区时间
	 *
	 * @param integer $gmtTime
	 */
	public function __construct($gmtTime)
	{
		$this->timestamp = $gmtTime + (self::$timezone - self::$serverTimezone) * 3600;
	}

	public static function setTimezone($timezone)
	{
		self::$timezone = $timezone;
		self::$serverTimezone = intval(idate('Z') / 3600);
	}

	public function format($format)
	{
		return date($format, $this->timestamp);
	}

	public function word()
	{
		return Tinyask_I18n::dateWord($this->timestamp, self::gmtTime() + (self::$timezone - self::$serverTimezone) * 3600);
	}

	public static function gmtTime()
	{
		return self::$gmtTimestamp ? self::$gmtTimestamp : (self::$gmtTimestamp = time());
	}

	public function __get($name)
	{
		switch($name) {
			case 'year':
				return date('Y', $this->timestamp);
			case 'month':
				return date('m', $this->timestamp);
			case 'day':
				return date('d', $this->timestamp);
			default:
				return '';
		}
	}
}
